<template>
  <div class="warehouseTransfers">
    <div class="warehouseTransfers_top">
      <p class="t_content1">调拨日期</p>
      <div class="block">
        <el-date-picker
          v-model="allotTime"
          type="date"
          style="width: 155px"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期"
        >
        </el-date-picker>
      </div>

      <p class="t_content">调入仓库</p>
      <input
        class="inp inp3"
        type="text"
        v-model="foldWarehouse"
        @blur="foldWarehouseBlur"
      />
      <el-select v-model="foldWarehouseName" @change="queryNo">
        <el-option
          v-for="item in manufacturerList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <p class="t_content">调出仓库</p>
      <input
        class="inp inp3"
        type="text"
        v-model="calloutWarehouse"
        @blur="calloutWarehouseBlur"
      />
      <el-select v-model="calloutWarehouseName" @change="queryNo1">
        <el-option
          v-for="item in warehouseList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <!-- <p class="t_content">款号</p>
      <input class="inp inp2" type="text" v-model="kindsNumber"> -->

      <p class="t_content">品名名称</p>
      <input class="inp inp2" type="text" v-model="commodityName" disabled />

      <p class="t_content">调拨序号</p>
      <input class="inp inp2" type="text" v-model="allotSequence" disabled />

      <p class="t_content">售价</p>
      <input class="inp inp2" type="text" v-model="sellingPrice" disabled />
    </div>

    <div class="warehouseTransfers_top2">
      <p class="remarks_1">备注</p>
      <input class="inp1 inp" type="text" v-model="remark" />
    </div>

    <div class="warehouseTransfers_c">
      <div class="content1">
        <div class="content1_1">
          <el-select
            v-model="reader"
            style="width: 90px; margin-right: 40px"
            disabled
          >
            <el-option
              v-for="item in readerList"
              :key="item.equipmentCabinetNo"
              :label="item.equipmentCabinetNo"
              :value="item.equipmentCabinetNo"
            >
            </el-option>
          </el-select>
          <el-button
            @click="readRFID"
            icon="el-icon-c-scale-to-original"
            disabled
            >读卡</el-button
          >
          <el-button @click="reduace" icon="el-icon-remove-outline" disabled
            >减标</el-button
          >
          <el-button @click="clearboth" icon="el-icon-delete" disabled
            >清空</el-button
          >
          <el-input v-model="searchRFID" style="width: 160px" disabled>
            <el-button @click="found" slot="append" class="found" disabled
              >寻标</el-button
            >
          </el-input>
        </div>
        <div class="c_tab">
          <el-table
            id="tip"
            :data="tabData"
            height="70vh"
            style="width: 100%"
            highlight-current-row
            @row-click="rowClick"
            ref="tabData"
            :header-cell-style="{
              background: '#f4f4f4',
              padding: 0,
              height: '40px'
            }"
            :cell-style="{ padding: 0, height: '36px' }"
          >
            <el-table-column type="selection" width="50"> </el-table-column>
            <el-table-column type="index" label="序号" width="50">
            </el-table-column>
            <el-table-column prop="showCode" label="RFID"> </el-table-column>
            <el-table-column
              prop="kindsNumber"
              show-overflow-tooltip
              label="款号"
            >
            </el-table-column>
            <el-table-column
              prop="sellingPrice"
              show-overflow-tooltip
              label="售价"
            >
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="content2">
        <div class="c2">
          <div class="c2_1">
            <el-button type="primary" icon="el-icon-plus" @click="shownewat"
              >新建</el-button
            >
            <el-button icon="el-icon-circle-check" @click="confirm"
              >确认</el-button
            >
            <!-- <el-button @click="()=>{this.showbudan='block'}" icon="el-icon-document-add">补单</el-button> -->
            <!-- <el-button @click="()=>{this.showpwd='block'}" icon="el-icon-edit-outline">改单</el-button> -->
            <!-- <el-button icon="el-icon-download">导入</el-button> -->
            <div class="dr">
              <i class="el-icon-download"></i>
              导入
              <input
                ref="upload"
                accept=".xls, .xlsx"
                class="outputlist_upload"
                type="file"
              />
            </div>
            <el-button @click="showprint" icon="el-icon-printer"
              >列印</el-button
            >
            <el-button @click="Delete" icon="el-icon-delete">删单</el-button>
          </div>

          <div class="c2_2">
            <p style="margin-right: 10px">数量：{{ howMany }}</p>
            <el-checkbox class="check" v-model="checked">二维</el-checkbox>
            <!-- <el-button icon="el-icon-arrow-left"></el-button>
            <el-button icon="el-icon-arrow-right"></el-button> -->
          </div>
        </div>

        <div class="content2_1">
          <el-table
            id="tip1"
            height="70vh"
            :data="tab1Data"
            ref="tab1Data"
            style="width: 100%"
            highlight-current-row
            :header-cell-style="{
              background: '#f4f4f4',
              padding: 0,
              height: '40px'
            }"
            :cell-style="{ padding: 0, height: '36px' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50"> </el-table-column>
            <el-table-column type="index" label="序号" width="50">
            </el-table-column>
            <template v-for="i in knhList">
              <el-table-column
                show-overflow-tooltip
                :prop="i.prop"
                :label="i.label"
                :width="i.width"
                :key="i.prop + Math.random()"
              >
              </el-table-column>
            </template>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 列印 -->
    <pr-int
      class="print"
      :style="{ display: SHprint }"
      @closeprint="closeprint"
    >
    </pr-int>

    <!-- <foot-view class="footView">
      <div slot="text">
        <el-popover
          placement="top-start"
          width="120"
          max-height="100px"
          trigger="click">
          <el-checkbox-group v-model="selectHeaderList" >
            <el-checkbox 
              v-for="i in headerList" 
              :label="i.value" 
              :key="i.value"
              style="margin-bottom:7px"></el-checkbox>
          </el-checkbox-group>
          <i slot="reference" class="el-icon-date">  表头配置</i>
        </el-popover>
        <span>数据库：倪姐夏18年2</span>
        <span>F7 设置扫描数量</span>
        <span>记录数：500</span>
      </div>
    </foot-view> -->

    <!-- 改单密码验证 -->
    <verify-password
      :style="{ display: showpwd }"
      @closepwd="
        () => {
          this.showpwd = 'none'
        }
      "
      @showRevision="showRevision"
    >
    </verify-password>

    <!-- 新建 这是一个组件-->
    <new-at
      v-if="isShowNewBuildDialog"
      @closeNewClerk="closeNewClerk"
      :sonFloortableData="sonFloortableData"
      @savenewAt="savenewAt"
      @keepSave="keepSave"
      @inpNumChange="
        () => {
          this.inpList = this.getInput()
        }
      "
      :detailInfo="details1"
      :diaobo_xuhaao="diaobo_xuhaao"
    >
      <!-- fei -->
      <!-- :seq="allotSequence" -->
    </new-at>

    <!-- 改单 -->
    <change-od
      :style="{ display: ChangeOd }"
      @closeChange="
        () => {
          this.ChangeOd = 'none'
        }
      "
      @saveChange="saveChange"
      :showData="this.tab1Data"
    >
    </change-od>

    <!-- 补单显示 -->
    <!-- <div class="budan" :style="{display:showbudan}">
      <div>
        <p>补单</p>
        <i class="el-icon-close" @click="()=>{this.showbudan='none'}"></i>
      </div>
      <div>
        <div style="margin-bottom:10px;"><p>补单单号</p></div>
        <el-input disabled v-model="showNum"></el-input>
        <div style="margin-top:10px;">
          <el-button @click="()=>{this.showbudan='none'}">取消</el-button>
          <el-button type="primary" @click="()=>{this.showsupOd='block'}">确定</el-button>
        </div>
      </div>
    </div> -->

    <!-- <sup-od
    :style="{display:showsupOd}"
    @closeSporder="()=>{this.showsupOd='none'}">
    </sup-od> -->
  </div>
</template>

<script>
import footView from '../../../components/FootView'
import newAt from './childComp/NewAt'
import {
  getManufacturer,
  factoryOut,
  AddWarehouse,
  confirmWarehouse,
  readRfid,
  DeleteOd,
  reduaceRfid,
  clearBoth
} from '../../../network/manufacturer'
import { getWarehouse } from '../../../network/warehouse'
import {
  UHFConnection,
  connectStatus,
  close,
  sendOrder,
  orderList,
  getUhfTest
} from '../../../network/rfid'
import { getBranded } from '../../../network/branded'
import today from '../../../components/mixins/today'
import verifyPassword from '../../../components/VerifyPassword'
import changeOd from './childComp/ChangeOd'
import supOd from './childComp/supOd'
import prInt from '../../../components/PrInt'
import { kindsNumberOut } from '../../../network/customerOutTotal'
import exportMethods from '../../../components/mixins/exportMethods'
import enterUp from '../../../components/mixins/enterUp'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import { internetProtocol } from '../../../config/ip'

export default {
  name: 'warehouse_transfers_wd',
  mixins: [today, exportMethods, enterUp],
  created() {
    // this.tab1Data = JSON.parse(localStorage.getItem('tabData'))
    this.inpList = this.getInput()
    this.allotTime = this.getNowTime()
    this.knhList = this.knhList1

    // 获取仓库信息
    getWarehouse().then((res) => {
      console.log(res.data.data)
      res.data.data.forEach((e) => {
        this.manufacturerList.push({ value: e.no, label: e.name })
        this.warehouseList.push({ value: e.no, label: e.name }) //调出
        if (e.isMainWarehouse == 1) {
          this.foldWarehouse = e.no
          this.foldWarehouseName = e.name
        }
      })
    })
    getUhfTest().then((res) => {
      this.readerList = res.data.data
      console.log(res.data)
      if (res.data.code == 200) {
        for (let z of res.data.data) {
          this.ip = z.ip
          this.port = z.port
          this.command = z.testHead + z.testBody
        }
        console.log(this.ip, Number(this.port), this.command)
      }
    })
  },
  data() {
    return {
      /* 传给子组件的调拨序号 */
      diaobo_xuhaao: '',
      /* 传给子组件底部的表格数组 */
      sonFloortableData: [],
      // 点击新建的时候，控制的字段
      newbuild: '',
      drc: '',
      dc: '',
      howMany: 0,
      reader: '',
      readerList: [],

      ip: '',
      port: '',
      command: '', //读卡参数
      dr: [],
      inpList: [],
      sid: '',
      RfidList: [],
      ti: [],
      ta: [],
      rwareHouse: '',
      cwareHouse: '',
      DList: [],
      manufacturerList: [],
      warehouseList: [],
      details1: {},
      tabData: [],
      searchRFID: [],

      details: [],
      showNum: '',
      // showbudan:'none',
      // showsupOd:'none',//补单
      ChangeOd: 'none',
      showpwd: 'none',

      tab1Data: [],
      allotTime: '',
      foldWarehouse: '',
      foldWarehouseName: '',
      calloutWarehouse: '',
      calloutWarehouseName: '',
      // kindsNumber:'',
      commodityName: '',
      allotSequence: '',
      sellingPrice: '',
      remark: '',
      SHprint: 'none',
      // radios:'1',
      showNewAt: 'none',
      isShowNewBuildDialog: false, // 点击新建的时候，弹出框
      checked: false,
      knhList: [],
      // 一维表格数据
      knhList1: [
        {
          prop: 'allotSequence',
          label: '调拨序号',
          width: '140'
        },
        {
          prop: 'foldWarehouse',
          label: '调入仓库',
          width: ''
        },
        {
          prop: 'calloutWarehouse',
          label: '调出仓库'
        },
        {
          prop: 'calloutWarehouseName',
          label: '调出仓名'
        },
        {
          prop: 'kindsNumber',
          label: '货号',
          width: '120'
        },
        {
          prop: 'sum',
          label: '数量',
          width: ''
        },
        {
          prop: 'allotTime',
          label: '调拨日期',
          width: '100'
        },
        {
          prop: 'remark',
          label: '备注',
          width: '150'
        },
        {
          prop: 'operator',
          label: '操作员',
          width: ''
        },
        {
          prop: 'enteringTime',
          label: '录入日期',
          width: '110'
        },
        {
          prop: 'status',
          label: '修改状态',
          width: ''
        }
      ],
      // 二维表格数据
      knhList2: [
        {
          prop: 'XH',
          label: '款号',
          width: '140'
        },
        {
          prop: 'colorName',
          label: '颜色名称',
          width: '80'
        },
        {
          prop: 'c05',
          label: '05-XS'
        },
        {
          prop: 'c07',
          label: '07-S',
          width: '70'
        },
        {
          prop: 'c09',
          label: '09-M',
          width: '70'
        },
        {
          prop: 'c11',
          label: '11-L',
          width: '70'
        },
        {
          prop: 'c13',
          label: '13-XL',
          width: '70'
        },
        {
          prop: 'c15',
          label: '15-2L',
          width: '70'
        },
        {
          prop: 'c17',
          label: '17-3L',
          width: '80'
        },
        {
          prop: 'c19',
          label: '19-4L',
          width: '80'
        },
        {
          prop: 'c21',
          label: '21-5L',
          width: '80'
        },
        {
          prop: 'c23',
          label: '23-6L',
          width: '80'
        },
        {
          prop: 'f',
          label: 'D',
          width: '70'
        },
        {
          prop: 'subtotal',
          label: '小计',
          width: ''
        },
        {
          prop: 'sellingPrice',
          label: '售价',
          width: ''
        },
        {
          prop: 'sellingPriceMoney',
          label: '售价金额',
          width: ''
        },
        {
          prop: 'brandedName',
          label: '品牌名称',
          width: '100'
        },
        {
          prop: 'quarter',
          label: '季度',
          width: ''
        }
      ],

      // 设置表头
      selectHeaderList: [],
      headerList: [],
      rfidList1: [],
      tabData: [],
      switchList: [],
      efficacious: [],
      /* 一个存删单字段的对象 */
      deleteParamsObj: {},
      /* 表格是否被多选的数据 */
      selectionTableManyRow: []
    }
  },
  watch: {
    checked(a, b) {
      var ssg = 'C08DDD'
      var olp = ssg.toLocaleLowerCase()
      console.log(olp)

      this.knhList = this.knhList2
      // console.log(this.knhList)
      console.log(this.tab1Data)
      if (a) {
        var ccun = {}
        for (let v in this.tab1Data) {
          this.tab1Data[v]['XH'] = this.tab1Data[v].kindsNumber.split('-')[0]
          this.tab1Data[v]['CC'] = this.tab1Data[v].kindsNumber
            .split('-')[1]
            .toLocaleLowerCase()
          console.log(this.tab1Data)
          for (let z in this.knhList2) {
            if (this.tab1Data.CC == this.knhList2[z].c09) {
              this.tab1Data.CC = this.tab1Data.number
            }
          }
          for (let m of this.knhList) {
            if (this.tab1Data[v].XH && this.tab1Data[v].CC == this.knhList[m]) {
              console.log(9851)
              console.log(this.tab1Data[v].XH)
              console.log(this.tab1Data[v].CC)
              this.tab1Data[v].CC = this.tab1Data[v].number
            }

            console.log(this.tab1Data[v].CC)
            this.tab1Data.forEach((e) => {
              ccun[e.kindsNumber] = e.number
            })
            this.tab1Data[v]['c05'] = this.tab1Data[v].number
            this.tab1Data[v]['c07'] = this.tab1Data[v].number
            this.tab1Data[v]['c09'] = this.tab1Data[v].number
            this.tab1Data[v]['c11'] = this.tab1Data[v].number
            this.tab1Data[v]['c13'] = this.tab1Data[v].number
            this.tab1Data[v]['c15'] = this.tab1Data[v].number
            this.tab1Data[v]['c17'] = this.tab1Data[v].number
            this.tab1Data[v]['c19'] = this.tab1Data[v].number
            this.tab1Data[v]['c21'] = this.tab1Data[v].number
            this.tab1Data[v]['c23'] = this.tab1Data[v].number
          }
          if (this.tab1Data[v].CC == 'C05') {
            this.tab1Data[v]['c05'] = this.tab1Data[v].number
          }
          if (this.tab1Data[v].CC == 'C07') {
            this.tab1Data[v]['c07'] = this.tab1Data[v].number
          }
          if (this.tab1Data[v].CC == 'C09') {
            this.tab1Data[v]['c09'] = this.tab1Data[v].number
          }
        }
        console.log(this.tab1Data)
      } else {
        this.knhList = this.knhList1
      }
    },
    calloutWarehouseName(a, b) {
      if (this.calloutWarehouse != '') {
        for (let c of this.warehouseList) {
          if (this.calloutWarehouse == c.value) {
            this.calloutWarehouseName = c.label
            return
          }
        }
      }
    }
  },
  components: {
    footView,
    verifyPassword,
    changeOd,
    supOd,
    newAt,
    prInt
  },
  methods: {
    // 监听子组件点击取消和关闭的事件
    closeNewClerk() {
      this.isShowNewBuildDialog = false
    },
    // 表格多选选中的是的时候，触发的函数
    handleSelectionChange(selection, row) {
      // 遍历拼接款号给后端
      console.log(selection)
      this.selectionTableManyRow = selection
      // 每一次都是清空这个对象
      this.deleteParamsObj = {}
      selection.forEach((item) => {
        this.deleteParamsObj[item.kindsNumber] = item.sum
      })
      console.log(this.deleteParamsObj)
    },
    // 删单
    Delete() {
      console.log('this.tab1Data', this.tab1Data)
      // if (this.allotSequence == '') {
      //   return
      // }
      for (let w of this.tab1Data) {
        // console.log(w.foldWarehouse,w.calloutWarehouse)
        this.drc = w.foldWarehouse
        this.dc = w.calloutWarehouse
      }
      this.ti = this.$refs.tab1Data.selection
      console.log('ti', this.ti)
      // if (this.ti.length == this.tab1Data.length && this.allotSequence != '') {
      //   // 如果是全部选中的话，就进来这里的逻辑
      //   // if (this.selectionTableManyRow.length) {
      //   this.$confirm('是否删除此调拨序号的所有货号数据 是否确认？', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     console.log('11111111111111')
      //     // DeleteOd(JSON.stringify({allotSequence:this.allotSequence,foldWarehouse:this.drc,calloutWarehouse:this.dc})).then(res=>{
      //     //   console.log(res.data)
      //     //   if(res.data.code == 200){
      //     //     this.$message({
      //     //       type: 'success',
      //     //       message: '删除成功'
      //     //     });
      //     //     this.tab1Data = []
      //     //     this.allotSequence = ''
      //     //     this.howMany = ''
      //     //   }else{
      //     //     this.$message.error({
      //     //       message: '删除失败'
      //     //     });
      //     //   }
      //     // })
      //     console.log('清空')
      //     // this.clearboth()
      //   })
      //   // } else if (this.ti != '' && this.allotSequence != '') {
      // } else if (this.selectionTableManyRow.length) {
      if (this.selectionTableManyRow.length) {
        console.log('进来发起ajax请求')
        var as = []
        var ad = []
        var af = {}
        for (let b in this.ti) {
          console.log(this.ti[b])
          // b.kindsNumber
          as.push(this.ti[b].kindsNumber)
          ad.push(this.ti[b].number)
          for (let s in as) {
            for (let d in ad) {
              if (s == d) {
                af[as[s]] = ad[s]
              }
            }
          }
        }
        this.$confirm('是否删除选中数据 是否确认？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var ol = {
            // kindsNumberMap: af,
            kindsNumberMap: this.deleteParamsObj,
            allotSequence: this.allotSequence,
            foldWarehouse: this.drc,
            calloutWarehouse: this.dc
          }
          // 删单的接口
          DeleteOd(JSON.stringify(ol)).then((res) => {
            console.log('DeleteOd', res.data)
            if (res.data.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              // this.allotSequence = ''
              this.howMany = ''
              this.ti.forEach((item, index) => {
                this.tab1Data.forEach((itemI, indexI) => {
                  if (item === itemI) {
                    this.tab1Data.splice(indexI, 1)
                  }
                })
              })
            } else {
              this.$message.error({
                message: '删除失败'
              })
            }
          })
        })
      }
    },
    //减标
    reduace() {
      if (this.allotSequence == '') {
        return
      }
      this.ta = this.$refs.tabData.selection
      if (this.ta == '') {
        this.$message({
          type: 'warning',
          message: '请选择减标数据'
        })
        return
      }
      var showCodeList1 = []
      this.ta.forEach((e) => {
        showCodeList1.push(e.id)
      })

      var ol1 = { rfidList: showCodeList1, allotSequence: this.allotSequence }
      console.log(ol1)
      this.$confirm('是否删除选中数据 是否确认？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (showCodeList1.length == this.ta.length) {
          console.log('清空')
          this.clearboth()
          return
        } else {
          reduaceRfid(JSON.stringify(ol1)).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.$message({
                type: 'success',
                message: '减标成功'
              })
              this.ta.forEach((item, index) => {
                this.tabData.forEach((itemI, indexI) => {
                  if (item === itemI) {
                    this.tabData.splice(indexI, 1)
                  }
                })
              })
              this.ta.forEach((item, index) => {
                this.tab1Data.forEach((item1, index1) => {
                  if (
                    item.kindsNumber == item1.kindsNumber &&
                    item1.number == 1
                  ) {
                    this.tab1Data.splice(index1, 1)
                  }
                  if (
                    item.kindsNumber == item1.kindsNumber &&
                    item1.number > 1
                  ) {
                    item1.number -= 1
                  }
                })
              }) //删除与左表关联的右表数据
            } else {
              this.$message.error({
                message: '减标失败'
              })
            }
          })
        }
      })
    },
    //清空
    clearboth() {
      this.$confirm('是否清空此调拨序号的RFID数据 是否确认？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        clearBoth({ allotSequence: this.allotSequence }).then((res) => {
          console.log(res.data)
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              message: '清空成功'
            })
            this.tabData.forEach((item, index) => {
              this.tab1Data.forEach((item1, index1) => {
                if (item.kindsNumber === item1.kindsNumber) {
                  this.tab1Data.splice(index1, 1)
                }
              })
            })
            this.tabData = []
          } else {
            this.$message.error({
              message: '减标失败'
            })
          }
        })
      })
    },
    //寻标
    found() {
      for (let c of this.tabData) {
        if (this.searchRFID == c.showCode) {
          this.tabData = [c]
        }
      }
    },

    rowClick(e) {
      this.details = e
      console.log(e)
    },
    //保存（监听子组件保存按钮的事件）
    savenewAt(data) {
      // this.showNewAt = 'none'
      console.log('点击保存拿到的参数', data)
      AddWarehouse(JSON.stringify(data)).then((res) => {
        //id方式
        // console.log(res.data.data.insertList)
        console.log('这里是父组件监听子组件的保存事件拿到的数据', res)
        if (res.data.code == 200) {
          // 传给子组件的调拨序号
          this.diaobo_xuhaao = res.data.data.sequence
          // 成功之后，还要拼接调拨序号进数组
          res.data.data.insertList.forEach((item) => {
            item.allotSequence = res.data.data.sequence
          })
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          /* 要传给子组件底部表格数据 */
          this.sonFloortableData = res.data.data.insertList
          console.log('sonFloortableData', this.sonFloortableData)

          this.DList = res.data.data
          // tab1Data是父组件右边表格用的数据
          this.tab1Data = res.data.data.insertList

          this.howMany = this.tab1Data.reduce((prev, next) => {
            //tab1Data数组里所有number的和
            // return prev + next.number
            return prev + next.sum
          }, 0)

          //   res.data.data.insertList.forEach(e=>{
          //   this.tab1Data.push(e)
          //   console.log(e)
          // })
          // localStorage.setItem('tabData',JSON.stringify(this.tab1Data))
          // this.tab1Data = JSON.parse(localStorage.getItem('tabData'))
          for (let y of this.tab1Data) {
            this.allotTime = y.allotTime
            this.foldWarehouse = y.foldWarehouse
            this.calloutWarehouse = y.calloutWarehouse
            // this.commodityName = y.commodityName
            this.allotSequence = y.allotSequence
            this.remark = y.remark
            this.rwareHouse = y.foldWarehouse
            this.cwareHouse = y.calloutWarehouse
          }

          if (res.data.data.validRfidList != undefined) {
            res.data.data.validRfidList.forEach((e) => {
              this.tabData.push(e)
            })
          }

          if (res.data.data.errorValidRfidList != undefined) {
            this.exportRaw(
              String(res.data.data.errorRfidList),
              '库存不足Rfid .txt'
            )
          }
        } else {
          this.$message.error({
            message: '保存失败'
          })
        }
      })
    },
    //继续录入
    keepSave(data) {
      AddWarehouse(JSON.stringify(data)).then((res) => {
        console.log(res.data)
        if (res.data.code == 200) {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.DList = res.data.data
          console.log(this.DList)
          res.data.data.insertList.forEach((e) => {
            this.tab1Data.push(e)
          })

          for (let y of this.tab1Data) {
            this.allotTime = y.allotTime
            this.foldWarehouse = y.foldWarehouse
            this.calloutWarehouse = y.calloutWarehouse
            // this.commodityName = y.commodityName
            this.allotSequence = y.allotSequence
            this.remark = y.remark
            this.rwareHouse = this.foldWarehouse
            this.cwareHouse = y.calloutWarehouse
          }

          if (res.data.data.validRfidList != undefined) {
            res.data.data.validRfidList.forEach((e) => {
              this.tabData.push(e)
            })
          }

          if (res.data.data.errorValidRfidList != undefined) {
            this.exportRaw(
              String(res.data.data.errorRfidList),
              '库存不足Rfid .txt'
            )
          }
        } else {
          this.$message.error({
            message: '保存失败'
          })
        }
      })
    },

    saveChange() {},
    //改单
    showRevision(data) {
      if (this.allotSequence == '') {
        return
      }
      this.showpwd = 'none'
      this.ChangeOd = 'block'
    },

    showprint() {
      this.SHprint = 'block'
    },
    closeprint() {
      this.SHprint = 'none'
    },

    cc() {
      this.details1 = {
        allotTime: this.allotTime,
        foldWarehouse: this.foldWarehouse,
        calloutWarehouse: this.calloutWarehouse,
        calloutWarehouseName: this.calloutWarehouseName,
        allotSequence: this.allotSequence,
        // kindsNumber:this.kindsNumber,
        remark: this.remark
      }
      console.log('details1', this.details1)
    },
    shownewat() {
      // 点击新建的时候，清空
      this.sonFloortableData = []
      // 序号清空
      this.diaobo_xuhaao = ''

      if (
        (this.rwareHouse,
        this.cwareHouse != '' &&
          (this.rwareHouse != this.foldWarehouse ||
            this.cwareHouse != this.calloutWarehouse))
      ) {
        this.$confirm('将创建新的调拨序号 是否确认？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.allotSequence = ''
          this.tabData = []
          this.tab1Data = []
          this.cc()
          // this.showNewAt = 'block'
          this.isShowNewBuildDialog = true
        })
      } else {
        this.cc()
        // this.showNewAt = 'block'
        this.isShowNewBuildDialog = true
      }
    },

    queryNo() {
      for (let c of this.manufacturerList) {
        if (this.foldWarehouseName == c.value) {
          this.foldWarehouse = c.value
          if (this.foldWarehouse == this.calloutWarehouse) {
            this.$message({
              type: 'warning',
              offset: 400,
              message: '调入仓库与调出仓库不能为同一个'
            })
            this.foldWarehouse = ''
            this.foldWarehouseName = ''
          }
          return
        }
      }
    },
    queryNo1() {
      for (let b of this.warehouseList) {
        if (this.calloutWarehouseName == b.value) {
          this.calloutWarehouse = b.value
          if (this.calloutWarehouse == this.foldWarehouse) {
            this.$message({
              type: 'warning',
              offset: 400,
              message: '调入仓库与调出仓库不能为同一个'
            })
            this.calloutWarehouse = ''
            this.calloutWarehouseName = ''
          }
          return
        }
      }
    },

    // 调入仓库失去焦点
    foldWarehouseBlur() {
      if (this.foldWarehouse != '') {
        for (let b of this.manufacturerList) {
          if (this.foldWarehouse == b.value) {
            this.foldWarehouseName = b.label
            return
          }
        }
        this.$message({
          type: 'warning',
          message: '无此仓库编号'
        })
        this.foldWarehouse = ''
        this.foldWarehouseName = ''
      } else {
        this.foldWarehouseName = ''
      }
    },
    //调出仓库编号失去焦点
    calloutWarehouseBlur() {
      if (this.calloutWarehouse != '') {
        for (let c of this.warehouseList) {
          if (this.calloutWarehouse == c.value) {
            this.calloutWarehouseName = c.label
            return
          }
        }
        this.$message({
          type: 'warning',
          message: '无此仓库编号'
        })
        this.calloutWarehouse = ''
        this.calloutWarehouseName = ''
      } else {
        this.calloutWarehouseName = ''
      }
    },

    // 读卡
    readRFID() {
      if (!this.reader) {
        this.$message({
          offset: 400,
          type: 'warning',
          message: '请选择读卡机'
        })
        return
      }
      if (!this.calloutWarehouse) {
        this.$message({
          offset: 400,
          type: 'warning',
          message: '仓库不能为空'
        })
        return
      }
      var sid = Math.random().toString(36).substring(2, 7)
      this.sid = sid
      var ws = new WebSocket(`wss://${internetProtocol}/webSocket/` + sid)
      ws.onopen = (e) => {
        // console.log(e)
        UHFConnection({
          host: this.ip,
          port: Number(this.port),
          socketId: sid
        }).then((res) => {})
        setTimeout(() => {
          connectStatus({ socketId: sid }).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.tabData = []
              if (!this.allotSequence) {
                this.rfidList1 = []
              }
              this.switchList = []
              this.efficacious = []
              this.$message.success({ message: '读卡器连接成功，开始读卡' })
              sendOrder({ command: this.command, connectId: this.sid }).then(
                (res) => {
                  console.log(res.data)
                }
              )
              this.loading = this.$loading({
                lock: true,
                text: '读卡中...',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, 0)'
              })
            } else if (res.data.code == 201) {
              this.$message.error({ message: '读卡器连接失败' })
            }
          })
        }, 1500)
      }
      ws.onmessage = (event) => {
        // console.log(event)       webSocket 发送信息
        if (event.data == '连接成功') return
        this.RfidList = JSON.parse(event.data)
        // console.log(this.RfidList) webSocket 发送信息
        if (this.RfidList.endCommand) {
          console.log(this.RfidList.endCommand)
          this.$message.success({ message: '读卡完成' })
          this.loading.close()
          ws.onclose()
          this.rfidAdd()
        }
        if (this.RfidList.isConnectError) {
          this.$message.error(
            `请检查路由器外网IP是否与此IP一致 ：${this.RfidList.connectTimeOutIp}`
          )
          this.loading.close()
          ws.close()
        }
        if (this.RfidList.validShowCode) {
          if (this.rfidList1.length) {
            let exist = 0
            for (const i of this.rfidList1) {
              if (i.showCode == this.RfidList.validShowCode) {
                exist = 1
                break
              }
            }
            if (!exist) {
              this.rfidList1.unshift({ showCode: this.RfidList.validShowCode })
              this.efficacious.push({ showCode: this.RfidList.validShowCode })
            }
          } else {
            this.rfidList1.unshift({ showCode: this.RfidList.validShowCode })
            this.efficacious.push({ showCode: this.RfidList.validShowCode })
          }
          this.tabData.unshift({
            showCode: this.RfidList.validShowCode,
            index: this.tabData.length + 1
          })
        }

        if (this.RfidList.otherErrorRFID) {
          if (this.tabData.length) {
            let exist = 0
            for (const i of this.tabData) {
              if (i.showCode.indexOf(this.RfidList.otherErrorRFID) != -1) {
                exist = 1
                break
              }
            }
            if (!exist) {
              this.tabData.unshift({
                showCode: this.RfidList.otherErrorRFID + '其他错误',
                index: this.tabData.length + 1
              })
            }
          } else {
            this.tabData.unshift({
              showCode: this.RfidList.otherErrorRFID + '其他错误',
              index: this.tabData.length + 1
            })
          }
        }

        if (this.RfidList.antennaErrorRFID) {
          if (this.tabData.length) {
            let exist = 0
            for (const i of this.tabData) {
              if (i.showCode.indexOf(this.RfidList.antennaErrorRFID) != -1) {
                exist = 1
                break
              }
            }
            if (!exist) {
              this.tabData.unshift({
                showCode:
                  this.RfidList.antennaErrorRFID +
                  '天线错误' +
                  this.RfidList.antennaErrorIndex,
                index: this.tabData.length + 1
              })
            }
          } else {
            this.tabData.unshift({
              showCode:
                this.RfidList.antennaErrorRFID +
                '天线错误' +
                this.RfidList.antennaErrorIndex,
              index: this.tabData.length + 1
            })
          }
        }
      }
      ws.onclose = () => {
        console.log('连接关闭')
        // close({socketId:this.sid}).then(res=>{
        //   console.log(res.data)
        // })
      }
      ws.onerror = (event) => {
        console.log(event)
      }
    },

    rfidAdd() {
      var rfidList = []

      this.tabData.forEach((e) => {
        rfidList.push(e.showCode)
      })
      let obj = {
        dataSource: 0,
        foldWarehouse: this.foldWarehouse,
        calloutWarehouse: this.calloutWarehouse,
        commodityName: this.commodityName,
        sellingPrice: this.sellingPrice,
        allotSequence: this.allotSequence,
        rfidList,
        allotTime: this.allotTime
      }
      console.log(obj)
      AddWarehouse(JSON.stringify(obj)).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          this.howMany = res.data.data.validRfidList.length
          this.tabData = []
          for (let a in res.data.data.insertList) {
            for (let b in this.warehouseList) {
              if (
                res.data.data.insertList[a].calloutWarehouse ==
                this.warehouseList[b].value
              ) {
                console.log('ajakak')
                res.data.data.insertList[a].calloutWarehouseName =
                  this.warehouseList[b].label
              }
            }
          }
          this.allotSequence = res.data.data.sequence
          res.data.data.validRfidList.forEach((e) => {
            this.tabData.push(e)
          })

          this.tab1Data = res.data.data.insertList
          if (res.data.data.errorRfidList != undefined) {
            // this.exportRaw(String(res.data.data.errorRfidList),'库存不足Rfid.txt')
          }
        }
      })
    },

    //确认
    confirm() {
      if (this.allotSequence == '') {
        return
      }
      this.$confirm('确认后不可对此单进行改单和补单操作 是否确认？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          confirmWarehouse({ allotSequence: this.allotSequence }).then(
            (res) => {
              console.log(res.data)
              if (res.data.code == 200) {
                for (let l of this.tab1Data) {
                  if (this.allotSequence == l.allotSequence) {
                    l.affirm = 1
                  }
                }
                console.log(this.tab1Data)
                this.$message({
                  type: 'success',
                  message: '确认成功!'
                })
              }
              // else {
              //   this.$message({
              //     type: 'info',
              //     message: '已取消确认'
              //   })
              // }
            }
          )
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //导入
    readExcel(e) {
      //表格导入
      var that = this
      const files = e.target.files
      console.log(files)
      if (files.length <= 0) {
        //如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0] //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
          console.log(ws)
          var ae = []
          var aw = []
          var ar = {}
          var at = []
          this.dr = []
          for (let v of ws) {
            console.log(v.调入仓库)
            if (v.数据来源 == 1) {
              ae.push(v.货号)
              aw.push(v.数量)
              for (var g in ae) {
                for (let n in aw) {
                  if (g == n) {
                    ar[ae[g]] = aw[n]
                  }
                }
              }
            } else if (v.数据来源 == 0) {
              for (let sl = 0; sl < v.数量; sl++) {
                at.push({ showCode: v.ID编号 })
              }
            }
            console.log(ar, at)

            this.dr.push({
              // allotTime: "2020-10-17 23:59:59",
              allotTime: v.调拨日期,
              allotSequence: v.调拨序号 == undefined ? '' : v.调拨序号,
              dataSource: v.数据来源,
              enteringTime: v.录入日期 == undefined ? '' : v.录入日期,
              startTime: v.开始时间 == undefined ? '' : v.录入时间,
              endTime: v.结束时间 == undefined ? '' : v.结束时间,
              foldWarehouse: v.调入仓库,
              calloutWarehouse: v.调出仓库,
              // kindsNumber:v.货号,
              remark: v.备注 == undefined ? '' : v.备注,
              sellPrice: v.售价 == undefined ? '' : v.售价,
              commodityName: v.品名名称 == undefined ? '' : v.品名名称,
              kindsNumberMap: ar,
              rfidList: at,
              receiptsNumber: v.单据号 == undefined ? '' : v.单据号
            })
          }
          console.log(this.dr)
          console.log(
            JSON.parse(JSON.stringify(this.dr[0]).replace(/^\[|\]$/g, ''))
          )
          // console.log(JSON.parse(JSON.stringify(this.dr).replace(/^\[|\]$/g,'')))
          AddWarehouse(
            JSON.parse(JSON.stringify(this.dr[0]).replace(/^\[|\]$/g, ''))
          ).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.$message({
                type: 'success',
                offset: 400,
                message: '导入成功!'
              })
              res.data.data.insertList.forEach((e) => {
                this.tab1Data.push(e)
              })

              if (res.data.data.validRfidList !== undefined) {
                res.data.data.validRfidList.forEach((e) => {
                  this.tabData.push(e)
                  console.log(this.tabData)
                })
              } else {
              }

              for (var c of this.tab1Data) {
                this.allotSequence = c.allotSequence
                console.log(this.allotSequence) //序号
                this.houseNo = c.warehouseNo
              }
              if (res.data.data.errorRfidList !== undefined) {
                this.exportRaw(
                  String(res.data.data.errorRfidList),
                  '库存不足Rfid.txt'
                )
              }

              this._getClient({ limit: this.limit, page: this.currentPage }) //重新请求页面数据
            } else {
              this.$message.error({
                offset: 400,
                message: '导入数据错误'
              })
            }
          })

          that.outputs = [] //清空接收数据
          //编辑数据
          for (var i = 0; i < ws.length; i++) {
            var sheetData = {
              address: ws[i].addr,
              value: ws[i].value
            }
            that.outputs.push(sheetData)
          }
          this.$refs.upload.value = ''
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    }
  },
  mounted() {
    this.$refs.upload.addEventListener('change', (e) => {
      //绑定监听表格导入事件
      this.readExcel(e)
    })
  }
}
</script>
<style scoped>
.warehouseTransfers {
  margin-right: 15px;
  padding: 0 15px;
  background-color: white;
  height: 94.5vh;
  position: relative;
}
.warehouseTransfers_top {
  display: flex;
  padding-top: 15px;
  white-space: nowrap;
}
.warehouseTransfers_top2 {
  height: 66px;
  padding-top: 15px;
  border-bottom: 2px solid #f4f4f4;
  display: flex;
  white-space: nowrap;
}

.warehouseTransfers_top2 input:last-child {
  width: 407px;
}
.t_content {
  margin: 0 6px 0 12px;
  padding-top: 3px;
}
.t_content1 {
  padding-top: 3px;
  margin: 0 6px 0 0;
}
.warehouseTransfers input:focus {
  outline: none;
  border: 1px solid #017aff;
}
.inp {
  border: 1px solid #dbdbdb;
  border-radius: 3px;
  height: 30px;
  padding: 0 15px;
}
.inp2 {
  width: 155px;
}
.inp1 {
  width: 200px;
}
.inp3 {
  width: 60px;
  margin-right: 10px;
}
.inp4 {
  width: 90px;
  margin-left: -1px;
}
.inp5 {
  width: 150px;
  margin: 0 0 0 16px;
}
.a_color {
  color: #017aff;
}
.warehouseTransfers_c {
  display: flex;
  width: 100%;
  height: 79%;
}
/*                   566464646*/
.content1 {
  width: 35%;
  border-right: 2px solid #f4f4f4;
  padding-right: 10px;
}
.content2 {
  width: 65%;
  /* height: 100%; */
  padding-left: 10px;
}
.content1_1 {
  display: flex;
  margin: 12px 0;
  overflow: hidden;
}
.c_button {
  width: 35px;
  height: 30px;
  margin: 0 0 0 -1px;
  /* padding:4px 6px 0 0; */
  background: #dbdbdb;
  font-size: 13px;
  border: 0px solid #dbdbdb;
  outline: none;
}
.hand {
  cursor: pointer;
}
.c2 {
  /* display: flex; */
  height: 40px;
  margin-top: 10px;
  flex-wrap: nowrap;
}
.c2_2 {
  height: 40px;
  float: right;
}
.c2_2 p {
  display: inline-block;
}
.c2_1 {
  display: inline-block;
  height: 40px;
}
.c2_2 p {
  margin: 4px 45px 0 0;
}
.check {
  width: 90px;
  height: 40px;
  border: 1px solid #d3cdcd;
  border-radius: 5px;
  padding: 8px 0 0 7px;
}
.c2_button {
  height: 25px;
  margin: 8px 5px 0 35px;
}
.c2_button1 {
  height: 25px;
  margin: 8px 5px 0 0;
}
.content2_1 {
  margin-top: 3px;
}
.date_1 {
  margin: 3px 6px 0 0;
}
.remarks_1 {
  margin: 3px 6px 0 32px;
}
.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.footView span i {
  margin-right: 5px;
}
.found {
  width: 60px;
}
.found:hover {
  background-color: #c6e2ff;
  color: #017fff;
}
.print {
  top: 19%;
  right: 30%;
}
.budan {
  position: absolute;
  top: 40%;
  left: 30%;
  width: 410px;
  height: 180px;
  background: white;
  box-shadow: 0 3px 3px 3px #f4f4f4;
}
.budan > div:first-child {
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  background: #f4f4f4;
}
.budan > div:nth-child(2) {
  padding: 10px 15px;
}
.budan > div:nth-child(2) > div:last-child {
  text-align: end;
}
.dr {
  margin-left: 10px;
}
</style>

<style>
.warehouseTransfers .el-input__icon {
  line-height: 30px;
}
.warehouseTransfers .warehouseTransfers_top .el-input__inner {
  height: 30px;
  width: 100px;
}
.warehouseTransfers .block .el-input__inner {
  width: 155px;
}
.warehouseTransfers .warehouseTransfers_top .ph .el-input__inner {
  height: 30px;
  width: 155px;
}
.warehouseTransfers .c_b .el-button {
  padding: 0;
}
.warehouseTransfers_top2 input[data-v-0deda660] {
  width: 155px;
  height: 30px;
}

.warehouseTransfers .content1_1 .el-input {
  width: 100px;
  margin-left: 10px;
}
.warehouseTransfers .content1_1 .el-input__inner {
  height: 30px;
}
.warehouseTransfers .c2_2 .check {
  width: 70px;
  height: 30px;
  padding: 3px 0 0 7px;
}

.warehouseTransfers .c2_2 .el-button {
  /* line-height: 0; */
  width: 40px;
}
.warehouseTransfers .c2_2 .el-button {
  margin: 0;
}
.warehouseTransfers .budan .el-input__inner {
  height: 30px;
}
.warehouseTransfers .el-input-group__append {
  background-color: #ecf5ff;
  color: #409eff;
}
</style>
